useThrottle 节流 和 useDebounce 防抖
useThrottle 节流
function useThrottle(fn, delay, dep = []) {
const { current } = useRef({ fn, timer: null });
useEffect(function () {
current.fn = fn;
}, []);
return useCallback((...args) => {
if (!current.timer) {
current.timer = setTimeout(() => {
delete current.timer;
}, delay);
current.fn.call(undefined, ...args);
}
}, dep);
}
const useThrottleMove = useThrottle(handle, 1000);
useDebounce 防抖
const useDebounce = (fn, delay, dep = []) => {
// 函数无状态,需要useRef声明引用,存储固定值 fn / time
const { current } = useRef({ fn, timer: null }); // 注意此时无数据fn 和 tiemr 为 undefined
useEffect(() => {
current.fn = fn;
}, []);
return useCallback((...args) => {
if (current.timer) {
clearTimeout(current.timer);
}
current.timer = setTimeout(() => {
current.fn.call(undefined, ...args);
}, delay);
}, dep);
};
const useDebounceMove = useDebounce(handle, 1000);